<template>
	<view class="container">
		<!-- 骨架屏 -->
		<view class="skeleton" v-if="loading">
			<view class="skeleton-header">
				<view class="skeleton-title"></view>
				<view class="skeleton-subtitle"></view>
			</view>
			<view class="skeleton-form">
				<view class="skeleton-input"></view>
				<view class="skeleton-input"></view>
			</view>
			<view class="skeleton-upload">
				<view class="skeleton-card"></view>
				<view class="skeleton-card"></view>
			</view>
		</view>
		
		<!-- 实际内容 -->
		<view class="content" v-else>
			<!-- 顶部提示 -->
			<view class="header">
				<view class="header-bg">
					<view class="circle-decoration"></view>
					<view class="light-effect"></view>
				</view>
				<view class="header-content">
					<view class="title-wrapper">
						<text class="title">实名认证</text>
						<view class="status-tag" :class="isVerified ? 'verified' : ''">
							{{ isVerified1 == -1 ? '未实名' : (isVerified1 == 0?"待审核中": (isVerified1 == 1? "已通过":"已拒绝")) }}
						</view>
					</view>
					<text class="subtitle">请填写真实身份信息，提交后不可修改</text>
					<text class="warning-text">24小时后还是审核状态说明没有通过认证</text>
				</view>
			</view>
			
			<!-- 表单区域 -->
			<view class="form-section">
				<view class="section-title">
					<view class="title-bar"></view>
					<text>基本信息</text>
				</view>
				<view class="form-card">
					<uni-forms ref="form" :modelValue="formData" :rules="rules">
						<!--  -->
						<uni-forms-item name="name" required>
							<view class="input-wrapper">
								<view class="icon-box">
									<uni-icons type="person-filled" size="20" color="#4A90E2"></uni-icons>
								</view>
								<uni-easyinput
									v-model="formData.name"
									placeholder="请输入真实姓名"
									@change="handleNameChange"
								/>
							</view>
						</uni-forms-item>
						
						<!-- 身份证号 -->
						<uni-forms-item name="idCard" required>
							<view class="input-wrapper">
								<view class="icon-box">
									<uni-icons type="vip-filled" size="20" color="#4A90E2"></uni-icons>
								</view>
								<uni-easyinput
									v-model="formData.idCard"
									placeholder="请输入身份证号码"
									@change="handleIdCardChange"
								/>
							</view>
						</uni-forms-item>
					</uni-forms>
				</view>
			</view>
			
			<!-- 证件上传 -->
			<view class="upload-section">
				<view class="section-title">
					<view class="title-bar"></view>
					<text>证件照片</text>
				</view>
				<view class="upload-header">
					<text class="subtitle">请上传本人有效身份的原件</text>
				</view>
				
				<view class="upload-grid">
					<!-- 身份证正面 -->
					<view class="upload-item">
						<text class="upload-label">
							<text class="required">*</text>
							身份证人像面
						</text>
						<view class="upload-content" :class="{'has-image': formData.idCardFront}">
							<view class="upload-box" @click="handleUpload('front')" v-if="!formData.idCardFront">
								<image class="guide-image" src="/static/images/id-front.png" mode="aspectFit"></image>
								<view class="upload-info">
									<uni-icons type="camera-filled" size="24" color="#4A90E2"></uni-icons>
									<text>点击上传人像面</text>
								</view>
								<view class="upload-border"></view>
							</view>
							<view class="preview-box" v-else>
								<image :src="formData.idCardFront" mode="aspectFill"></image>
								<view class="preview-overlay">
									<view class="preview-actions">
										<button class="action-btn" @click.stop="handlePreview('front')">
											<uni-icons type="eye-filled" size="18" color="#fff"></uni-icons>
											<text>预览</text>
										</button>
										<button class="action-btn" @click.stop="handleUpload('front')">
											<uni-icons type="upload-filled" size="18" color="#fff"></uni-icons>
											<text>重新上传</text>
										</button>
									</view>
								</view>
							</view>
						</view>
					</view>
					
					<!-- 身份证反面 -->
					<view class="upload-item">
						<text class="upload-label">
							<text class="required">*</text>
							身份证国徽面
						</text>
						<view class="upload-content" :class="{'has-image': formData.idCardBack}">
							<view class="upload-box" @click="handleUpload('back')" v-if="!formData.idCardBack">
								<image class="guide-image" src="/static/images/id-back.png" mode="aspectFit"></image>
								<view class="upload-info">
									<uni-icons type="camera-filled" size="24" color="#4A90E2"></uni-icons>
									<text>点击上传国徽面</text>
								</view>
								<view class="upload-border"></view>
							</view>
							<view class="preview-box" v-else>
								<image :src="formData.idCardBack" mode="aspectFill"></image>
								<view class="preview-overlay">
									<view class="preview-actions">
										<button class="action-btn" @click.stop="handlePreview('back')">
											<uni-icons type="eye-filled" size="18" color="#fff"></uni-icons>
											<text>预览</text>
										</button>
										<button class="action-btn" @click.stop="handleUpload('back')">
											<uni-icons type="upload-filled" size="18" color="#fff"></uni-icons>
											<text>重新上传</text>
										</button>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 提示信息 -->
			<view class="tips-section">
				<view class="tip-card">
					<view class="tip-title">
						<uni-icons type="info-filled" size="16" color="#FFA550"></uni-icons>
						<text>温馨提示</text>
					</view>
					<view class="tip-item">
						<uni-icons type="checkmarkempty" size="14" color="#FFA550"></uni-icons>
						<text>请确保证件在有效期内且信息清晰可见</text>
					</view>
					<view class="tip-item">
						<uni-icons type="checkmarkempty" size="14" color="#FFA550"></uni-icons>
						<text>您的信息将被严格保密，仅用于身份验证</text>
					</view>
				</view>
			</view>
			
			<!-- 提交按钮 -->
			<view class="submit-section">
				<button 
					class="submit-btn" 
					:disabled="!canSubmit"
					:class="{ 'submit-btn-active': canSubmit }"
					@click="handleSubmit"
				>
					<text>{{ isVerified ? '已完成认证' : '提交认证' }}</text>
					<view class="btn-light" v-if="canSubmit"></view>
					<view class="btn-icon" v-if="isVerified">
						<uni-icons type="checkmarkempty" size="18" color="#fff"></uni-icons>
					</view>
				</button>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import request from "@/common/request.js"
import { STORAGE_KEY, updateStorageField } from '../../common/config';
import {onLoad} from "@dcloudio/uni-app"
onLoad(() => {
})
// 表单数据
const formData = ref({
	name: '',
	idCard: '',
	idCardFront: '',
	idCardBack: '',
	user_id: 0
})

// 表单校验规则
const rules = {
	name: {
		rules: [{
			required: true,
			errorMessage: '请输入姓名'
		}]
	},
	idCard: {
		rules: [{
			required: true,
			errorMessage: '请输入身份证号'
		}, {
			pattern: /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dX]$/,
			errorMessage: '身份证号格式不正确'
		}]
	}
}

// 认证状态文本
const statusText = computed(() => {
	if(!formData.value.name || !formData.value.idCard) {
		return '请填写真实身份信息'
	}
	if(!formData.value.idCardFront || !formData.value.idCardBack) {
		return '请上传身份证照片'
	}
	return '信息已填写完整,请提交认证'
})

// 表单项变处理函数
const handleNameChange = () => {}
const handleIdCardChange = () => {}

// 处理预览
const handlePreview = (type) => {
	const current = type === 'front' ? formData.value.idCardFront : formData.value.idCardBack
	const urls = [formData.value.idCardFront, formData.value.idCardBack].filter(Boolean)
	
	uni.previewImage({
		current: current,
		urls: urls,
		indicator: 'number',
		loop: true,
		success: () => {
			console.log('预览成功')
		},
		fail: (err) => {
			console.error('预览失败:', err)
			uni.showToast({
				title: '预览失败',
				icon: 'none'
			})
		}
	})
}

// 处理上传
const handleUpload = (type) => {
	if(isVerified.value) {
		uni.showToast({
			title: '已完成实名认证,不可修改',
			icon: 'none'
		})
		return
	}
	uni.showActionSheet({
		itemList: ['拍照', '从相册选择'],
		success: (res) => {
			uni.chooseImage({
				count: 1,
				sourceType: res.tapIndex === 0 ? ['camera'] : ['album'],
				sizeType: ['compressed'],
				success: (res) => {
					// 检查图片大小
					const tempFilePath = res.tempFilePaths[0]
					uni.getFileInfo({
						filePath: tempFilePath,
						success: (fileInfo) => {
							// 限制图片大小为10MB
							if(fileInfo.size > 10 * 1024 * 1024) {
								uni.showToast({
									title: '图片大小不能超过10MB',
									icon: 'none'
								})
								return
							}
							
							// 更新对应的图片
							if(type === 'front') {
								formData.value.idCardFront = tempFilePath
							} else {
								formData.value.idCardBack = tempFilePath
							}
						}
					})
				},
				fail: (err) => {
					console.error('选择图片失败:', err)
					uni.showToast({
						title: '选择图片失败',
						icon: 'none'
					})
				}
			})
		}
	})
}

// 是否可提交
const canSubmit = computed(() => {
	return formData.value.name && 
		formData.value.idCard && 
		formData.value.idCardFront && 
		formData.value.idCardBack
})

// 表单引用
const form = ref(null)

// 提交处理
const handleSubmit = () => {
	if(isVerified1.value != -1) {
		uni.showToast({
			title: '已提交审核, 不可重复喔!',
			icon: 'none'
		})
		return
	}
	form.value.validate().then(res => {
		uni.showLoading({
			title:"提交中",
			mask:true,
		})
		setTimeout(() => {
			uni.hideLoading()
			uni.uploadFile({
				url:request.baseURL + "api/user/smrz/",
				files: [
					{name: "id_card_front_image", uri: formData.value.idCardFront},
					{name: "id_card_back_image", uri: formData.value.idCardBack},
					
				],
				fileType: "image",
				formData: {
					user: formData.value.user_id,
					idCard: formData.value.idCard,
					name: formData.value.name
				},
				success: (res) => {
					res.data = JSON.parse(res.data)
					const MsgType = res.data.code == 200 ? "success" : "error";
					uni.showToast({
						title: res.data.msg,
						icon:MsgType
					})
					
					if(res.data.code == 200) {
						res.data.data.id_card_back_image = request.baseURL.slice(0, -1) + res.data.data.id_card_back_image
						res.data.data.id_card_front_image = request.baseURL.slice(0, -1) + res.data.data.id_card_front_image
						uni.setStorageSync(STORAGE_KEY.USER_CARD, JSON.stringify(res.data.data))
						
						// 更新用户信息中的认证状态
						const userInfo = JSON.parse(uni.getStorageSync(STORAGE_KEY.USER_INFO))
						userInfo.user_is_authenticated = 0 // 提交后等待审核
						uni.setStorageSync(STORAGE_KEY.USER_INFO, JSON.stringify(userInfo))
						// 显示等待审核提示
						uni.showToast({
							title: '提交成功,等待审核',
							icon: 'success',
							duration: 2000
						})
					}
				}
			})
		}, 1200)
	})
}

// 添加loading状态
const loading = ref(true)
const isVerified = ref(false)
let isVerified1 = ref(-1) // 认证状态

// 检查认证状态
const checkVerifyStatus = () => {
	const userInfo = uni.getStorageSync(STORAGE_KEY.USER_INFO)
	const userCard = uni.getStorageSync(STORAGE_KEY.USER_CARD)
	
	if (userInfo && userCard) {
		const userInfoData = JSON.parse(userInfo)
		const cardInfo = JSON.parse(userCard)
		
		// 填充表单数据
		formData.value.name = cardInfo.name
		formData.value.idCard = cardInfo.idCard
		formData.value.idCardFront = cardInfo.id_card_front_image
		formData.value.idCardBack = cardInfo.id_card_back_image
		if (userInfoData.user_is_authenticated) {
			// 认证通过
			isVerified.value = true
			// 禁用所有输入和上传功能
			disableForm('已完成实名认证')
			// 显示认证通过提示
			uni.showToast({
				title: '您已通过实名认证',
				icon: 'success',
				duration: 2000
			})
		} else if (cardInfo) {
			// 认证未通过或审核中
			isVerified.value = false 
			disableForm('实名认证审核中')
			// 显示认证未通过提示
			uni.showToast({
				title: '实名正在审核中',
				icon: 'none',
				duration: 2000
			})
		}
	}
}

// 禁用表单
const disableForm = (btnText = '已完成实名认证') => {
	// 禁用姓名和身份证输入
	const inputs = document.querySelectorAll('.uni-easyinput__content-input')
	inputs.forEach(input => {
		input.setAttribute('disabled', true)
	})
	
	// 隐藏上传按钮和预览操作
	const uploadActions = document.querySelectorAll('.preview-actions')
	uploadActions.forEach(action => {
		action.style.display = 'none'
	})
	
	// 修改提交按钮
	const submitBtn = document.querySelector('.submit-btn')
	if(submitBtn) {
		submitBtn.setAttribute('disabled', true)
		submitBtn.textContent = btnText
		
		// 认证未通过时按钮样式
		if(btnText === '实名认证未通过') {
			submitBtn.style.background = '#ff4d4f'
		}
	}
}

// 检查实名认证状态
const check_real_name_auth_status = () => {
	request.get("api/user/smrz/").then(res => {
		formData.value.idCardFront = request.baseURL.slice(0, -1) + res.data.id_card_front_image
		formData.value.idCardBack = request.baseURL.slice(0, -1) + res.data.id_card_back_image
		formData.value.name = res.data.name
		formData.value.idCard = res.data.idCard
		formData.value.user_id = res.data.user
		isVerified1.value = res.data.user_info.user_is_authenticated
		updateStorageField(STORAGE_KEY.USER_INFO, "user_is_authenticated", res.data.user_info.user_is_authenticated)
	}).finally(() => {
		loading.value = false
	})

}

// 在 onMounted 中调用检查
onMounted(() => {

	
	const userInfo = JSON.parse(uni.getStorageSync(STORAGE_KEY.USER_INFO) || "{user_id: 0}")
	if(userInfo) {
		formData.value.user_id = userInfo.id
		check_real_name_auth_status()
	}
	
	
	
})
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	background-color: #f5f6fa;
	position: relative;
}

/* 骨架屏样式 */
.skeleton {
	padding: 30rpx;
	
	@keyframes skeleton-loading {
		0% { background-position: 100% 50%; }
		100% { background-position: 0 50%; }
	}
	
	.skeleton-header, .skeleton-input, .skeleton-card {
		background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 37%, #f0f0f0 63%);
		background-size: 400% 100%;
		animation: skeleton-loading 1.4s ease infinite;
	}
	
	.skeleton-title {
		height: 40rpx;
		width: 200rpx;
		margin-bottom: 16rpx;
	}
	
	.skeleton-subtitle {
		height: 28rpx;
		width: 300rpx;
	}
	
	.skeleton-form {
		margin: 50rpx 0;
		.skeleton-input {
			height: 96rpx;
			border-radius: 12rpx;
			margin-bottom: 30rpx;
		}
	}
	
	.skeleton-upload {
		display: flex;
		justify-content: space-between;
		.skeleton-card {
			width: 320rpx;
			height: 200rpx;
			border-radius: 12rpx;
		}
	}
}

/* 实际内容样式 */
.content {
	padding: 30rpx;
}

.header {
	position: relative;
	padding: 40rpx 30rpx;
	margin: -30rpx -30rpx 50rpx;
	background: linear-gradient(135deg, #4A90E2, #357ABD, #2C5C8F);
	border-radius: 0 0 30rpx 30rpx;
	overflow: hidden;
	
	.header-bg {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		overflow: hidden;
		
		.circle-decoration {
			position: absolute;
			right: -100rpx;
			top: -100rpx;
			width: 300rpx;
			height: 300rpx;
			border-radius: 50%;
			background: rgba(255,255,255,0.1);
		}
		
		.light-effect {
			position: absolute;
			top: -100%;
			left: -100%;
			right: -100%;
			bottom: -100%;
			background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0) 70%);
			animation: rotate 10s linear infinite;
		}
	}
	
	.header-content {
		position: relative;
		z-index: 1;
	}
	
	.title-wrapper {
		display: flex;
		align-items: center;
		gap: 20rpx;
		margin-bottom: 20rpx;
	}
	
	.title {
		font-size: 44rpx;
		font-weight: bold;
		color: #fff;
		position: relative;
		display: block;
	}
	
	.status-tag {
		padding: 4rpx 16rpx;
		background: rgba(255,255,255,0.2);
		border-radius: 20rpx;
		font-size: 24rpx;
		color: #fff;
		
		&.verified {
			background: rgba(39,194,129,0.2);
			color: #27C281;
		}
	}
	
	.subtitle {
		font-size: 28rpx;
		color: rgba(255,255,255,0.8);
		position: relative;
		display: block;
		margin-bottom: 8rpx;
	}
	
	.warning-text {
		font-size: 24rpx;
		color: #FFE162;
		display: block;
	}
}

.section-title {
	display: flex;
	align-items: center;
	gap: 16rpx;
	margin-bottom: 20rpx;
	
	.title-bar {
		width: 6rpx;
		height: 32rpx;
		background: #4A90E2;
		border-radius: 3rpx;
	}
	
	text {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}
}

.form-card {
	background: #fff;
	border-radius: 20rpx;
	padding: 30rpx;
	box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.05);
	
	.input-wrapper {
		display: flex;
		align-items: center;
		background-color: #F8F9FC;
		border-radius: 12rpx;
		padding: 0 30rpx;
		
		:deep(.uni-easyinput) {
			flex: 1;
			margin-left: 20rpx;
			
			.uni-easyinput__content {
				min-height: 96rpx;
				background: none;
			}
		}
	}
}

.upload-section {
	margin: 30rpx 0;
	background: #fff;
	border-radius: 20rpx;
	padding: 30rpx;
	box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.05);
	
	.upload-header {
		margin-bottom: 30rpx;
		
		.title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 8rpx;
			display: block;
		}
		
		.subtitle {
			font-size: 26rpx;
			color: #999;
		}
	}
	
	.upload-grid {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 30rpx;
		
		.upload-item {
			.upload-label {
				font-size: 28rpx;
				color: #333;
				margin-bottom: 16rpx;
				display: block;
			}
			
			.upload-content {
				position: relative;
				width: 100%;
				border-radius: 12rpx;
				overflow: hidden;
				
				&.has-image {
					box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
				}
				
				.upload-box {
					width: 100%;
					aspect-ratio: 1.6;
					background: #F8F9FC;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					position: relative;
					
					.guide-image {
						width: 80%;
						height: 120rpx;
						object-fit: contain;
						margin-bottom: 20rpx;
					}
					
					.upload-info {
						display: flex;
						flex-direction: column;
						align-items: center;
						gap: 8rpx;
						
						text {
							font-size: 26rpx;
							color: #4A90E2;
						}
					}
					
					.upload-border {
						position: absolute;
						top: 8rpx;
						left: 8rpx;
						right: 8rpx;
						bottom: 8rpx;
						border: 2rpx dashed #4A90E2;
						border-radius: 8rpx;
						pointer-events: none;
					}
					
					&:active {
						background: #F0F2F8;
					}
				}
				
				.preview-box {
					width: 100%;
					aspect-ratio: 1.6;
					position: relative;
					
					image {
						width: 100%;
						height: 100%;
						object-fit: cover;
					}
					
					.preview-overlay {
						position: absolute;
						top: 0;
						left: 0;
						width: 100%;
						height: 100%;
						background: rgba(0,0,0,0.5);
						opacity: 1;
						transition: opacity 0.3s;
						display: flex;
						align-items: center;
						justify-content: center;
						
						.preview-actions {
							display: flex;
							gap: 20rpx;
							
							.action-btn {
								background: rgba(255,255,255,0.2);
								border: none;
								padding: 16rpx 24rpx;
								border-radius: 8rpx;
								display: flex;
								flex-direction: column;
								align-items: center;
								gap: 8rpx;
								min-width: 120rpx;
								
								text {
									font-size: 24rpx;
									color: #fff;
								}
								
								&:active {
									background: rgba(255,255,255,0.3);
								}
							}
						}
					}
					
					&:active {
						.preview-overlay {
							opacity: 1;
						}
					}
				}
			}
		}
	}
}

.tip-card {
	background: #FFF9F2;
	border-radius: 12rpx;
	padding: 20rpx;
	box-shadow: 0 4rpx 20rpx rgba(255,165,80,0.1);
	
	.tip-title {
		display: flex;
		align-items: center;
		gap: 8rpx;
		margin-bottom: 16rpx;
		
		text {
			font-size: 28rpx;
			font-weight: bold;
			color: #FFA550;
		}
	}
	
	.tip-item {
		display: flex;
		align-items: center;
		gap: 8rpx;
		margin-top: 12rpx;
		
		text {
			font-size: 26rpx;
			color: #666;
		}
	}
}

.required {
	color: #ff4d4f;
	margin-right: 4rpx;
}

.submit-section {
	margin-top: 80rpx;
	padding: 0 30rpx;
	
	.submit-btn {
		position: relative;
		width: 100%;
		height: 88rpx;
		line-height: 88rpx;
		text-align: center;
		background: #E5E6EB;
		color: #999;
		border-radius: 44rpx;
		font-size: 32rpx;
		overflow: hidden;
		
		&.submit-btn-active {
			background: linear-gradient(135deg, #4A90E2, #357ABD);
			color: #fff;
			box-shadow: 0 8rpx 16rpx rgba(74,144,226,0.3);
			
			.btn-light {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
				animation: btnShine 2s infinite;
			}
		}
		
		&:active {
			transform: scale(0.98);
		}
	}
}

@keyframes rotate {
	from { transform: rotate(0deg); }
	to { transform: rotate(360deg); }
}

@keyframes cornerShine {
	0% { transform: rotate(45deg) translateY(0); opacity: 0; }
	50% { transform: rotate(45deg) translateY(200rpx); opacity: 1; }
	100% { transform: rotate(45deg) translateY(400rpx); opacity: 0; }
}

@keyframes btnShine {
	from { transform: translateX(-100%); }
	to { transform: translateX(100%); }
}
</style>
